package com.exam.Service;

import com.exam.Entity.Admin;
import com.exam.Entity.CustomUserDetails;
import com.exam.Entity.Student;
import com.exam.Entity.Teacher;
import com.exam.Mapper.LoginMapper;

import com.exam.aopsolution.TimeKeeping;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

@Service
public class LoginService {

    @Autowired
    private LoginMapper loginMapper;


    public Admin adminLogin(Integer username, String password) {
        return loginMapper.adminLogin(username,password);
    }


    public Teacher teacherLogin(Integer username, String password) {
        return loginMapper.teacherLogin(username,password);
    }


    public Student studentLogin(Integer username, String password) {
        return loginMapper.studentLogin(username,password);
    }

    @TimeKeeping
    public CustomUserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        CustomUserDetails user = loginMapper.loadStudentByUsername(username);
        if (user != null) {
            user.setType("student");

            return user;
        }

        user = loginMapper.loadTeacherByUsername(username);
        if (user != null) {
            user.setType("teacher");
            return user;
        }

        user = loginMapper.loadAdminByUsername(username);
        if (user != null) {
            user.setType("admin");
            return user;
        }

        // 如果用户不存在，抛出异常
        throw new UsernameNotFoundException("User not found: " + username);
    }

}
